﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using W.Purchase.API.Application.Command.PayableCommand;
using W.Purchase.Domain;
using W.Purchase.Repository.Impl;
using W.Purchase.Repository.Interface;

namespace W.Purchase.API.Application.CommandHandler.PayableCommandHandler
{
    public class ActuallypaidCreateCommandHandler:IRequestHandler<ActuallypaidCreateCommand,int>
    {
        private readonly IPayableRepository _ipayableRepository;
        private readonly IActuallypaidRepository _iactuallypaidRepository;
        public ActuallypaidCreateCommandHandler(IPayableRepository ipayableRepository, IActuallypaidRepository iactuallypaidRepository)
        {
            _ipayableRepository = ipayableRepository;
            _iactuallypaidRepository = iactuallypaidRepository;
        }

        public async Task<int> Handle(ActuallypaidCreateCommand request, CancellationToken cancellationToken)
        {
            using (var tran = _iactuallypaidRepository.DB.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
            {
                try
                {
                    #region 实付信息表添加数据
                    Actuallypaid actuallypaid = new Actuallypaid();
                    actuallypaid.PayableSerialNumber = request.PayableSerialNumber;
                    actuallypaid.PayerDepartment = request.PayerDepartment;
                    actuallypaid.FinanceTypeName = request.FinanceTypeName;
                    actuallypaid.EndDate = request.EndDate;
                    actuallypaid.PayMoney = request.PayMoney;
                    actuallypaid.Actualpaymentremark = request.Actualpaymentremark;
                    await _iactuallypaidRepository.AddAsync(actuallypaid);
                    #endregion

                    #region 修改应付表数据
                    var list = await _ipayableRepository.GetAllAsaync();
                    var plist = list.Where(c => c.PayableSerialNumber == actuallypaid.PayableSerialNumber).FirstOrDefault();
                    if (plist != null)
                    {
                        plist.PayableId = plist.PayableId;
                        plist.ActuallyPaidMoney += actuallypaid.PayMoney;
                        plist.ResidueMoney = plist.PayableMoney - actuallypaid.PayMoney;
                        await _ipayableRepository.Update(plist);
                    }
                    #endregion
                    var code = await _iactuallypaidRepository.DB.SaveChangesAsync();
                    tran.Commit();
                    return code;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return 1;
                }
            }
        }
    }
}
